package com.youlai.boot.modules.content.service.impl;

import com.youlai.boot.core.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.modules.content.mapper.LzLinkMapper;
import com.youlai.boot.modules.content.service.LzLinkService;
import com.youlai.boot.modules.content.model.entity.LzLink;
import com.youlai.boot.modules.content.model.form.LzLinkForm;
import com.youlai.boot.modules.content.model.query.LzLinkQuery;
import com.youlai.boot.modules.content.model.vo.LzLinkVO;
import com.youlai.boot.modules.content.converter.LzLinkConverter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 友链服务实现类
 *
 * @author lz006891
 * @since 2025-02-25 10:49
 */
@Service
@RequiredArgsConstructor
public class LzLinkServiceImpl extends ServiceImpl<LzLinkMapper, LzLink> implements LzLinkService {

    private final LzLinkConverter lzLinkConverter;

    /**
    * 获取友链分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<LzLinkVO>} 友链分页列表
    */
    @Override
    public IPage<LzLinkVO> getLzLinkPage(LzLinkQuery queryParams) {
        Page<LzLinkVO> pageVO = this.baseMapper.getLzLinkPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取友链表单数据
     *
     * @param id 友链ID
     * @return
     */
    @Override
    public LzLinkForm getLzLinkFormData(Long id) {
        LzLink entity = this.getById(id);
        return lzLinkConverter.toForm(entity);
    }
    
    /**
     * 新增友链
     *
     * @param formData 友链表单对象
     * @return
     */
    @Override
    public boolean saveLzLink(LzLinkForm formData) {
        LzLink entity = lzLinkConverter.toEntity(formData);
        entity.setCreateBy(SecurityUtils.getUserId());
        entity.setUpdateBy(SecurityUtils.getUserId());
        return this.save(entity);
    }
    
    /**
     * 更新友链
     *
     * @param id   友链ID
     * @param formData 友链表单对象
     * @return
     */
    @Override
    public boolean updateLzLink(Long id,LzLinkForm formData) {
        LzLink entity = lzLinkConverter.toEntity(formData);
        entity.setUpdateBy(SecurityUtils.getUserId());
        return this.updateById(entity);
    }
    
    /**
     * 删除友链
     *
     * @param ids 友链ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteLzLinks(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的友链数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
